import { createRouter, createWebHistory } from 'vue-router'

// 添加路由守卫日志
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { public: true } // 标记为公开路由
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { title: '首页' }
      },
      {
        path: '/customer',
        name: 'CustomerManagement',
        component: () => import('@/views/customer/CustomerManagement.vue'),
        meta: { title: '客户管理' }
      },
      {
        path: '/system/user',
        name: 'UserManagement',
        component: () => import('@/views/system/UserManagement.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: '/system/role',
        name: 'RoleManagement',
        component: () => import('@/views/system/RoleManagement.vue'),
        meta: { title: '角色管理' }
      },
      {
        path: '/profile',
        name: 'UserProfile',
        component: () => import('@/views/profile/UserProfile.vue'),
        meta: { title: '个人信息' }
      },
      {
        path: '/test-form-controls',
        name: 'TestFormControls',
        component: () => import('@/views/TestFormControls.vue'),
        meta: { title: '表单控件测试' }
      },
      {
        path: '/test-form-controls2',
        name: 'TestFormControls2',
        component: () => import('@/views/TestFormControls2.vue'),
        meta: { title: '表单控件测试2' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

import { useUserStore } from '@/store/user'

// 添加路由导航守卫
router.beforeEach(async (to, from, next) => {
  console.log(`路由跳转: ${from.path} => ${to.path}`)
  
  try {
    const userStore = useUserStore()
    
    // 确保store已初始化
    if (!userStore || typeof userStore.isLoggedIn !== 'function') {
      console.error('用户store未正确初始化')
      return next('/login')
    }

    const isPublic = to.matched.some(record => record.meta.public)
    
    // 公开路由直接放行
    if (isPublic) {
      // 如果已登录访问登录页，重定向到首页
      if (to.path === '/login' && userStore.isLoggedIn()) {
        return next('/')
      }
      return next()
    }

    // 受保护路由检查登录状态
    if (!userStore.isLoggedIn()) {
      return next('/login')
    }

    // 已登录但缺少用户信息，尝试获取
    if (!userStore.userInfo) {
      await userStore.getUserInfo()
    }

    next()
  } catch (error) {
    console.error('路由守卫错误:', error)
    return next('/login')
  }
})

router.afterEach((to) => {
  console.log('成功跳转到:', to.path)
})

export default router